"""This module contains functions used by the proper programs.

Most notably, it defines functions responsible for reading/writing data and
handling errors that may pop up in the process:
konfigurator() - parses options.cfg and passes variables to the calling module,
czytacz() - parses the database and passes data structured as lists,
pisacz() - accepts data structured as lists and writes them to the database.
"""

def konfigurator(which_script):
    """Parses options.cfg and handles errors.
    """

    import ConfigParser
    import time
    config = ConfigParser.RawConfigParser()
    config.read('options.cfg')
    
    if which_script == "shuffle":
        try:
            trick_pause = config.getint('Options','trick_pause')
        except ValueError:
            print "   Invalid trick_pause option. Setting to default (0)."
            trick_pause = 0
            time.sleep(3)
        try:
            trick_count = config.getint('Options','trick_count')
        except ValueError:
            print "   Invalid trick_count option. Setting to default (5)."
            trick_count = 5
            time.sleep(3)
        try:
            weak_grade = config.getfloat('Options','weak_grade')
        except ValueError:
            print "   Invalid weak_grade option. Setting to default (5)."
            weak_grade = 5
            time.sleep(3)
        try:
            recent_count = config.getint('Options','recent_count')
        except ValueError:
            print "   Invalid recent_count option. Setting to default (5)."
            recent_count = 5
            time.sleep(3)
        return trick_pause, trick_count, weak_grade, recent_count
    elif which_script == "analyze":
        try:
            trust_thresh = config.getint('Options','trust_thresh')
        except ValueError:
            print "   Invalid trust_thresh option. Setting to default (5)."
            trust_thresh = 5
            time.sleep(3)
        return trust_thresh
    elif which_script == "claymotion":
        try:
            clay_components = config.get('Options','clay_components')
        except ValueError:
            print "   Invalid claymotion_components option. Setting to default."
            clay_components = "Claw Catch, Penguin Catch, Orbit, Cross-Arm"
            time.sleep(3)
        try:
            clay_count = config.getint('Options', 'clay_count')
        except ValueError:
            print "   Invalid clay_count option. Setting to default (3)."
            clay_count = 3
            time.sleep(3)
        return clay_components, clay_count
    elif which_script == "challenge":
        try:
            challenge_list = config.get('Options','challenge_list')
        except ValueError:
            print "   Invalid challenge_list option. Setting to default."
            challenge_list = "10 QRs, 20 QRs, 30 QRs, 1 min, 2 min, 3 min"
            time.sleep(3)
        return challenge_list
    else:
        try:
            grade_count = config.getint('Options','grade_count')
        except ValueError:
            print "   Invalid grade_count option. Setting to default (5)."
            grade_count = 5
            time.sleep(3)
        try:
            grades_to_store = config.getint('Options','grades_to_store')
        except ValueError:
            print "   Invalid grades_to_store option. Setting to default (10)."
            grades_to_store = 10
            time.sleep(3)
        return grade_count, grades_to_store


def czytacz():
    """Parses the database.
    """

    import csv

    trick_list = []
    grades_string_list = []
    tag_string_list = []
    
    f = open("patterns.csv", "rb")
    #reads database entries, constructs lists
    temp_list = csv.reader(f)
    for pattern, grades, tags in temp_list:
        trick_list.append(pattern)
        grades_string_list.append(grades)
        tag_string_list.append(tags)

    # removes CSV headers
    del trick_list[0]
    del grades_string_list[0]
    del tag_string_list[0]
    
    f.close()

    return trick_list, grades_string_list, tag_string_list


def pisacz(trick_list, grades_string_list, tag_string_list):
    """Accepts lists and writes data to the database.
    """
    
    import csv

    f = open("patterns.csv", "wb")
    logWriter = csv.writer(f)
    logWriter.writerow(['pattern','grades','tags'])
    for zlicz in range(0, len(trick_list)):
        logWriter.writerow([trick_list[zlicz].strip(), grades_string_list[zlicz], tag_string_list[zlicz]])
    f.close()
